home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / screen-resolution-extra / screenresolution-mechanism.pyc (.txt) < prev   
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  11.9 KB  |  299 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''
  5. Processes, which want to access this service have to acquire first
  6. the action id "com.ubuntu.xkit.mechanism.configure" from PolicyKit
  7. '''
  8. import dbus
  9. import dbus.service as dbus
  10. import gobject
  11. import logging
  12. import os
  13. import os.path as os
  14. import sys
  15. from XKit import xutils, xorgparser
  16. import time
  17. import shutil
  18. import subprocess
  19. POLICY_KIT_ACTION = 'com.ubuntu.screenresolution.mechanism.configure'
  20.  
  21. class PolicyKitAuthentication(object):
  22.     '''
  23.     Helper class to do authentication via PolicyKit
  24.     '''
  25.     
  26.     def __init__(self):
  27.         super(PolicyKitAuthentication, self).__init__()
  28.         self._PolicyKitAuthentication__pk = None
  29.         self._PolicyKitAuthentication__pa = None
  30.  
  31.     
  32.     def is_authorized(self, action_id, pid = None):
  33.         '''
  34.         Ask PolicyKit whether we are already authorized.
  35.         '''
  36.         if pid == None:
  37.             pid = os.getpid()
  38.         
  39.         pid = dbus.UInt32(pid)
  40.         authorized = self.policy_kit.IsProcessAuthorized(action_id, pid, False)
  41.         logging.debug('%s: authorized=%r', action_id, authorized)
  42.         return 'yes' == authorized
  43.  
  44.     
  45.     def obtain_authorization(self, action_id, widget = None):
  46.         '''
  47.         Try to obtain authoriztation for the specified action.
  48.         '''
  49.         if self.is_authorized(action_id):
  50.             return True
  51.         if not widget or widget.get_toplevel().window.xid:
  52.             pass
  53.         xid = 0
  54.         xid = dbus.UInt32(xid)
  55.         pid = dbus.UInt32(os.getpid())
  56.         granted = self.auth_agent.ObtainAuthorization(action_id, xid, pid)
  57.         logging.debug('%s: granted=%r', action_id, granted)
  58.         return bool(granted)
  59.  
  60.     
  61.     def __get_policy_kit(self):
  62.         '''Retreive the D-Bus interface of PolicyKit.'''
  63.         if self._PolicyKitAuthentication__pk:
  64.             return self._PolicyKitAuthentication__pk
  65.         service = dbus.SystemBus().get_object('org.freedesktop.PolicyKit', '/')
  66.         self._PolicyKitAuthentication__pk = dbus.Interface(service, 'org.freedesktop.PolicyKit')
  67.         return self._PolicyKitAuthentication__pk
  68.  
  69.     
  70.     def __get_auth_agent(self):
  71.         '''Retreive the D-Bus interface of the PolicyKit authentication agent.'''
  72.         if self._PolicyKitAuthentication__pa:
  73.             return self._PolicyKitAuthentication__pa
  74.         self._PolicyKitAuthentication__pa = dbus.SessionBus().get_object('org.freedesktop.PolicyKit.AuthenticationAgent', '/')
  75.         return self._PolicyKitAuthentication__pa
  76.  
  77.     auth_agent = property(__get_auth_agent)
  78.     policy_kit = property(__get_policy_kit)
  79.  
  80.  
  81. try:
  82.     from dbus.lowlevel import HANDLER_RESULT_NOT_YET_HANDLED
  83. except ImportError:
  84.     from _dbus_bindings import HANDLER_RESULT_NOT_YET_HANDLED
  85.  
  86.  
  87. class AccessDeniedException(dbus.DBusException):
  88.     '''This exception is raised when some operation is not permitted.'''
  89.     _dbus_error_name = 'com.ubuntu.screenresolution.Mechanism.AccessDeniedException'
  90.  
  91.  
  92. class UnsupportedException(dbus.DBusException):
  93.     '''This exception is raised when some operation is not supported.'''
  94.     _dbus_error_name = 'com.ubuntu.screenresolution.Mechanism.UnsupportedException'
  95.  
  96.  
  97. class UsageError(dbus.DBusException):
  98.     '''This exception is raised when some operation was not used properly.'''
  99.     _dbus_error_name = 'com.ubuntu.screenresolution.Mechanism.UsageError'
  100.  
  101.  
  102. class PolicyKitService(dbus.service.Object):
  103.     '''A D-BUS service that uses PolicyKit for authorization.'''
  104.     
  105.     def _check_permission(self, sender, action = POLICY_KIT_ACTION):
  106.         '''
  107.         Verifies if the specified action is permitted, and raises
  108.         an AccessDeniedException if not.
  109.  
  110.         The caller should use ObtainAuthorization() to get permission.
  111.  
  112.         Needs:
  113.         /usr/bin/polkit-auth --user root --grant org.freedesktop.policykit.read
  114.  
  115.         '''
  116.         if not sender:
  117.             raise AccessDeniedException('Session not authorized by PolicyKit')
  118.         sender
  119.         
  120.         try:
  121.             policy_auth = PolicyKitAuthentication()
  122.             bus = dbus.SystemBus()
  123.             dbus_object = bus.get_object('org.freedesktop.DBus', '/')
  124.             dbus_object = dbus.Interface(dbus_object, 'org.freedesktop.DBus')
  125.             kit = bus.get_object('org.freedesktop.PolicyKit', '/')
  126.             kit = dbus.Interface(kit, 'org.freedesktop.PolicyKit')
  127.             pid = dbus.UInt32(dbus_object.GetConnectionUnixProcessID(sender))
  128.             granted = policy_auth.is_authorized(action, pid)
  129.             logging.info('process authorization: %r', granted)
  130.             print >>sys.stderr, 'process authorization: %r' % granted
  131.             if not granted:
  132.                 raise AccessDeniedException('Process not authorized by PolicyKit')
  133.             granted
  134.             granted = policy_auth.policy_kit.IsSystemBusNameAuthorized(action, sender, False)
  135.             logging.info('authorization of system bus name: %r', granted)
  136.             if 'yes' != granted:
  137.                 raise AccessDeniedException('Session not authorized by PolicyKit')
  138.             'yes' != granted
  139.         except AccessDeniedException:
  140.             logging.info('AccessDeniedException')
  141.             raise 
  142.         except dbus.DBusException:
  143.             ex = None
  144.             logging.info('AccessDeniedException %r', ex)
  145.             raise AccessDeniedException(ex.message)
  146.  
  147.  
  148.  
  149.  
  150. class BackendService(PolicyKitService):
  151.     '''A D-Bus service that PolicyKit controls access to.'''
  152.     INTERFACE_NAME = 'com.ubuntu.ScreenResolution.Mechanism'
  153.     SERVICE_NAME = 'com.ubuntu.ScreenResolution.Mechanism'
  154.     IDLE_TIMEOUT = 30
  155.     
  156.     def __init__(self, connection = None, path = '/'):
  157.         if connection is None:
  158.             connection = get_service_bus()
  159.         
  160.         super(BackendService, self).__init__(connection, path)
  161.         self._BackendService__name = dbus.service.BusName(self.SERVICE_NAME, connection)
  162.         self._BackendService__loop = gobject.MainLoop()
  163.         self._BackendService__timeout = 0
  164.         connection.add_message_filter(self._BackendService__message_filter)
  165.  
  166.     
  167.     def __message_filter(self, connection, message):
  168.         '''
  169.         D-BUS message filter that keeps the service alive,
  170.         as long as it receives message.
  171.         '''
  172.         if self._BackendService__timeout:
  173.             self._BackendService__start_idle_timeout()
  174.         
  175.         return HANDLER_RESULT_NOT_YET_HANDLED
  176.  
  177.     
  178.     def __start_idle_timeout(self):
  179.         '''Restarts the timeout for terminating the service when idle.'''
  180.         if self._BackendService__timeout:
  181.             gobject.source_remove(self._BackendService__timeout)
  182.         
  183.         self._BackendService__timeout = gobject.timeout_add(self.IDLE_TIMEOUT * 1000, self._BackendService__timeout_cb)
  184.  
  185.     
  186.     def __timeout_cb(self):
  187.         '''Timeout callback that terminates the service when idle.'''
  188.         if self.connection.list_exported_child_objects('/'):
  189.             return True
  190.         print 'Terminating %s due to inactivity.' % self.SERVICE_NAME
  191.         self._BackendService__loop.quit()
  192.         return False
  193.  
  194.     
  195.     def run(self):
  196.         '''Creates a GLib main loop for keeping the service alive.'''
  197.         print 'Running %s.' % self.SERVICE_NAME
  198.         print 'Terminating it after %d seconds of inactivity.' % self.IDLE_TIMEOUT
  199.         self._BackendService__start_idle_timeout()
  200.         self._BackendService__loop.run()
  201.  
  202.     
  203.     def setVirtual(self, virtres, sender = None):
  204.         '''
  205.         Replace the first line of this example with a source and a destination file
  206.         '''
  207.         virtual = ' '.join(virtres)
  208.         source = '/etc/X11/xorg.conf'
  209.         destination = '/etc/X11/xorg.conf'
  210.         if os.path.exists(source):
  211.             backup = source + '.' + time.strftime('%Y%m%d%H%M%S')
  212.             shutil.copyfile(source, backup)
  213.         
  214.         
  215.         try:
  216.             a = xutils.XUtils(source)
  217.         except (IOError, xorgparser.ParseException):
  218.             a = xutils.XUtils()
  219.  
  220.         empty = True
  221.         for section in a.globaldict:
  222.             if len(a.globaldict[section]) > 0:
  223.                 empty = False
  224.                 break
  225.                 continue
  226.         
  227.         if empty:
  228.             a.makeSection('Device', 'Configured Video Device')
  229.             a.makeSection('Screen', identifier = 'Configured Screen Device')
  230.             a.addReference('Screen', 'Device', 'Configured Video Device', position = 0)
  231.             a.makeSubSection('Screen', 'Display', position = 0)
  232.             a.addSubOption('Screen', 'Display', 'Virtual', value = virtual, position = 0)
  233.         else:
  234.             devicelen = len(a.globaldict['Device'])
  235.             screenlen = len(a.globaldict['Screen'])
  236.             if screenlen == 0:
  237.                 screen = a.makeSection('Screen', identifier = 'Configured Screen Device')
  238.                 if devicelen == 0:
  239.                     device = a.makeSection('Device', 'Configured Video Device')
  240.                 else:
  241.                     device = 0
  242.                 a.addReference('Screen', 'Device', 'Configured Video Device', position = device)
  243.                 a.makeSubSection('Screen', 'Display', position = 0)
  244.                 a.addSubOption('Screen', 'Display', 'Virtual', value = virtual, position = 0)
  245.             else:
  246.                 for screen in a.globaldict['Screen']:
  247.                     a.makeSubSection('Screen', 'Display', position = screen)
  248.                     a.addSubOption('Screen', 'Display', 'Virtual', value = virtual, position = screen)
  249.                 
  250.         a.writeFile(destination)
  251.         return True
  252.  
  253.     setVirtual = dbus.service.method(dbus_interface = INTERFACE_NAME, in_signature = 'as', out_signature = 'b', sender_keyword = 'sender')(setVirtual)
  254.     
  255.     def setDontZap(self, enable, sender = None):
  256.         '''Try to set the DontZap option in the xorg.conf
  257.            and return the exit code of dontzap'''
  258.         dontzap_file = '/usr/bin/dontzap'
  259.         if not os.path.isfile(dontzap_file):
  260.             logging.error('/usr/bin/dontzap does not exist')
  261.             return 1
  262.         if enable in ('--enable', '--disable'):
  263.             logging.debug('calling dontzap with %s' % enable)
  264.             retcode = subprocess.call([
  265.                 dontzap_file,
  266.                 enable])
  267.             return retcode
  268.         logging.error('called with wrong arguments = %s' % enable)
  269.         return 1
  270.  
  271.     setDontZap = dbus.service.method(dbus_interface = INTERFACE_NAME, in_signature = 's', out_signature = 'i', sender_keyword = 'sender')(setDontZap)
  272.  
  273.  
  274. def get_service_bus():
  275.     '''Retrieves a reference to the D-BUS system bus.'''
  276.     return dbus.SystemBus()
  277.  
  278.  
  279. def get_service(bus = None):
  280.     '''Retrieves a reference to the D-BUS driven configuration service.'''
  281.     if not bus:
  282.         bus = get_service_bus()
  283.     
  284.     service = bus.get_object(BackendService.SERVICE_NAME, '/')
  285.     service = dbus.Interface(service, BackendService.INTERFACE_NAME)
  286.     return service
  287.  
  288. if __name__ == '__main__':
  289.     import sys
  290.     from sys import argv
  291.     from dbus.mainloop.glib import DBusGMainLoop
  292.     DBusGMainLoop(set_as_default = True)
  293.     if '--debug' in argv or '-d' in argv:
  294.         logging.basicConfig(stream = sys.stderr)
  295.         logging.getLogger().setLevel(logging.NOTSET)
  296.     
  297.     BackendService().run()
  298.  
  299.